<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Management extends CI_Controller {

    /**
     * 系统设置控制器
     * @2017.3.1
     * 
     */
    function __construct() {
        parent::__construct();
        $this->load->model('User_m', 'm');
        $this->load->model('Function_m', 'fun');
        $this->pageSize = $this->config->item('pagenum');
    }

    public function webset() {
        //print_r($this->config->item('webmenu'));
        $this->tpl->display("management/webset.tpl");
    }

    public function syscenter() {
        $rsdb = $this->fun->getconfig();
        $this->tpl->assign("rsdb", $rsdb);
        $this->tpl->display("management/syscenter.tpl");
    }

    function saveconfig() {
        $webdbs = $this->input->post('webdbs');
        $this->fun->write_config_cache($webdbs);
        header("location:/management/syscenter");
    }

    public function setshop() {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;

        $where = " AND openflag =1";
        $other = trim($this->input->get_post('other'));
        if ($other) {
            $where .= " AND (name like '%" . $other . "%'  or updateoper like '%" . $other . "%' or id = '".$other."' )";
            $this->tpl->assign("other", $other);
        }
		$platformID = $this->input->get_post('platformID');
        if ($platformID) {
            $where .= " AND platfrom = '".$platformID."'";
            $this->tpl->assign("platformID", $platformID);
        }
        $list = $this->fun->getalllist('`d_shop`', $where, $nowpage, $if_csv, $this->pageSize);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("list", $list["list"]);
		$this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));
        $this->tpl->display("management/setshop.tpl");
    }

    public function factory() {

        $this->tpl->assign("list", $this->m->getFactoryList());
        $this->tpl->display("management/factory.tpl");
    }

    public function addFactory() {

        if (empty($_POST)) {

            $this->tpl->display("management/addFactory.tpl");
        } else {

            $this->m->saveAddFactory();
            header("location: /management/factory");
        }
    }

    public function editFactory() {

        if (empty($_POST)) {

            $result = $this->m->getFactoryRow();
            $this->tpl->assign("detail", $result[0]);
            $this->tpl->display("management/editFactory.tpl");
            unset($result);
        } else {

            $this->m->saveEditFactory();
            header("location: /management/factory");
        }
    }

    public function delFactory() {

        $this->m->delFactory();
        header("location: /management/factory");
    }

    public function platform() {

        $this->tpl->assign("list", $this->m->getPlatformList());
        $this->tpl->display("management/platform.tpl");
    }

    public function addPlatform() {

        if (empty($_POST)) {

            $this->tpl->display("management/addPlatform.tpl");
        } else {

            $this->m->saveAddPlatform();
            header("location: /management/platform");
        }
    }

    public function editPlatform() {

        if (empty($_POST)) {

            $result = $this->m->getPlatformRow();
            $this->tpl->assign("detail", $result[0]);
            $this->tpl->display("management/editPlatform.tpl");
        } else {

            $this->m->saveEditPlatform();
            header("location: /management/platform");
        }
    }

    public function delPlatform() {

        $this->m->delPlatform();
        header("location: /management/platform");
    }

    public function userlist() {
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;


        $where = " ";
        $starttime = trim($_POST["starttime"]);
        if ($starttime) {
            $createtime = $starttime . " 00:00:00";
            $where .= " AND createtime >='" . $createtime . "'";
            $this->tpl->assign("starttime", $starttime);
        }
        $endtime = trim($this->input->post('endtime'));
        if ($endtime) {
            $createtime1 = $endtime . " 23:59:59";
            $where .= " AND createtime <='" . $createtime1 . "'";
            $this->tpl->assign("endtime", $endtime);
        }
        $other = $this->input->post('other');
        if ($other) {
            $where .= " AND (name like '%" . $other . "%' or username like '%" . $other . "%')";
            $this->tpl->assign("other", $other);
        }

        $department = $this->input->post('classid');
        if ($department) {
            $where .= " AND (classid =" . $department . ")";
            $this->tpl->assign("_department", $department);
        }
        $classid = $this->input->post('department');
        if ($classid) {
            $where .= " AND (department =" . $classid . ")";
            $this->tpl->assign("_classid", $classid);
        }


        $id = $this->input->get('id');
        if ($id) {
            $where .= " AND id='" . $id . "'";
        }

        $result_department = $this->fun->getDepartment();
        $result_classid = $this->fun->getClassId();
        $this->tpl->assign("department", $result_department);
        $this->tpl->assign("classid", $result_classid);

        $list = $this->fun->getalllist('d_user', $where, $nowpage, $if_csv, $this->pageSize);
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("list", $list["list"]);
        $this->tpl->display("management/userlist.tpl");
    }

    public function menulist(){
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;

        $result_department = $this->fun->getDepartment();
        $result_classid = $this->fun->getClassId();
        $this->tpl->assign("department", $result_department);
        $this->tpl->assign("classid", $result_classid);
        $where=" and sort_id=0";
        $list = $this->fun->getalllist('d_menu', $where, $nowpage, $if_csv, $this->pageSize," order by sort_id asc,sort asc");
        $newmenulist=array();
        foreach($list['list'] as $key=>$menuval){
            $menuval['value_txt']="<strong>".$menuval['value_txt']."</strong>";
            $newmenulist[]=$menuval;
            $chirdmenu=$this->getChildMenu($menuval['id']);
            foreach($chirdmenu as $index=>$chirdarr){
                $newmenulist[]=$chirdarr;
            }
        }


        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("list", $newmenulist);
        $this->tpl->display("management/menulist.tpl");
    }

    public function getChildMenu($pid)
    {
        $datalist=array();
        $list = $this->fun->getalllist('d_menu', " and sort_id=$pid", $nowpage, $if_csv, $this->pageSize," order by sort_id asc,sort asc");
        foreach($list['list'] as $key=>$secondmenu){
            $secondmenu['value_txt']="<img src='\\fuman\images\line_link.gif'><img src='\\fuman\images\line_parent_child.gif'>".$secondmenu['value_txt'];
            $datalist[]=$secondmenu;
            $thirdmenulist = $this->fun->getalllist('d_menu', " and sort_id=$secondmenu[id]", $nowpage, $if_csv, $this->pageSize," order by sort_id asc,sort asc");
            foreach($thirdmenulist['list'] as $key=>$thirdmenu) {
                $thirdmenu['value_txt']="<img src='\\fuman\images\line_link.gif'><img src='\\fuman\images\line_link.gif'><img src='\\fuman\images\line_parent_child.gif'>".$thirdmenu['value_txt'];
                $datalist[] = $thirdmenu;
            }
        }
        //dump($datalist);die;
        return $datalist;
    }


	
	/*外部组员工管理*************/
    public function externaluser()
	{
		$this->tpl->assign("list", $this->db->get('d_user_external')->result_array());
		
		$this->tpl->assign("userlist", $this->db->get_where('d_user',"classid = 14 and type = 1")->result_array());
        $this->tpl->display("management/externaluser.tpl");
	}

    public function ajaxbutton() {
      $op = $this->input->get_post('op');

        /*     * ******
     * * 开发人员工具,设置整个系统连接，
     * * 权限等功能
     * */
        if($op=='addsys_menu'){
            $menudb = $this->m->getmenudblink();
            $this->tpl->assign("menudblist", $menudb);
            $this->tpl->display("management/development.tpl");
            die;
        }
        if ($op == "addmenu") {
            $menuid = $this->input->get_post('id');
            $this->tpl->assign("m",$this->fun->getdatabasesdetail('d_menu'," AND id = $menuid"));
            $menudb = $this->m->getmenudblink();
            $this->tpl->assign("menudblist", $menudb);

            $this->tpl->assign("history_url", $_SERVER['HTTP_REFERER']);
            $this->tpl->display("management/editmenu.tpl");
            die;
        }
        if ($op == "do_editmenu") {
            $postdata["value_txt"] = $this->input->post('name');
            $postdata["value_fied"] = $this->input->post('tlinks');
            $postdata["power"] = $this->input->post('power');
            $postdata["sort_id"] = $this->input->post('sort_id');
            $postdata["sort"] = $this->input->post('sort');
            $postdata["isshow"] = $this->input->post('isshow');

            $id= $this->input->post('id');
            //dump($postdata);die;
            $res = $this->db->query($this->db->update_string('d_menu', $postdata," id = '".$id."'"));

            header("Location:".$this->input->post('historyurl'));
            die;
        }
        if ($op == "savevalue") {
            $valuetxt = $this->input->post('valuetxt');
            $value_fied = $this->input->post('value_fied');
            $power = $this->input->post('power');
            $remark = $this->input->post('remark');
            $sort_id = $this->input->post('sort_id');
            $id = $this->input->post('id');
            $sort = $this->input->post('sort');
            $isshow = $this->input->post('isshow');
            $rs = $this->m->savevalue($valuetxt, $value_fied, $power, $remark, $sort_id, $id, $sort, $isshow);
            echo $rs;
            die;
        }
		
		if($op =='saveattribute')
		{
			 $name = $this->input->post('name');
            if ($name == "") {
                $this->fun->phpalert(2, "名称必须填写！");
                die;
            }
            $postdata["external_name"] = $this->input->post('name');
            $postdata["is_stop"] = 0;
            $res = $this->db->query($this->db->insert_string('d_user_external', $postdata));
            $this->fun->phpalert(4, "", '', "/management/externaluser");
            die;
		}
		if($op =='delexternaluser')
		{
			 $id = $this->input->post('id');
			 $is_top = $this->input->post('is_top');
			 if($is_top)
			{
				$is_top =0;
			}else{
				$is_top = 1;
			}
            $postdata["is_stop"] = $is_top;
            $res = $this->db->query($this->db->update_string('d_user_external', $postdata," id = '".$id."'"));
            $this->fun->phpalert(4, "", '', "/management/externaluser");
            die;
		}
		if($op =='opengoods')
		{
			 $id = $this->input->post('id');
			 $is_open = $this->input->post('is_open');
			 if($is_open)
			{
				$is_open =0;
			}else{
				$is_open = 1;
			}
            $postdata["is_opengoods"] = $is_open;
            $res = $this->db->query($this->db->update_string('d_user_external', $postdata," id = '".$id."'"));
            $this->fun->phpalert(4, "", '', "/management/externaluser");
            die;
		}
		if($op =='saveexternaluser')
		{
			$cat_id = $this->input->post('cat_id');
			$attr_name = $this->input->post('attr_name');
			if(!$attr_name)
			{
				 $this->fun->phpalert(2, "名称必须填写！");
                die;
			}

			$attr_name = explode(",",$attr_name);
			$attr_name = implode("','",$attr_name);
			$username = $this->fun->getdatabasesdetail('d_user'," AND classid = 14 and type = 1 and name in('".$attr_name."')","GROUP_CONCAT(id) as userid,GROUP_CONCAT(name) as username ");
			
			$postdata= "";
			$postdata["external_user"] = trim($username['username']);
			$postdata["external_userID"] = trim($username['userid']);
			$this->db->update("d_user_external",$postdata," id ='".$cat_id."'");
			  $this->fun->phpalert(4, "", '', "/management/externaluser");
            die;
		}

        if ($op == "cechelink") {
            $rs = $this->m->write_config_menu();
            echo $rs;
        }
		if ($op == "editshop") {
			$res = $this->fun->getdatabasesdetail('d_shop'," AND id='".intval($this->input->get('id'))."'");
          
           
			 $this->tpl->assign("detail", $res);
			 $this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));
			 $this->tpl->assign("userlist", $this->fun->getdatabaseslist('d_user', " AND type = 1", '*', ' order by id desc'));
			 //店铺分类
			 $shopgroup =$this->fun->get_sys_goods_status('sys_shop_group');
			 $this->tpl->assign("shopgroup", $shopgroup);
             $this->tpl->display("management/editshop.tpl");
        }
        if ($op == "addshop") {
            $this->tpl->assign("platform", $this->fun->getdatabaseslist('db_platform'));
            $this->tpl->assign("userlist", $this->fun->getdatabaseslist('d_user', " AND type = 1", '*', ' order by id desc'));
			 $shopgroup =$this->fun->get_sys_goods_status('sys_shop_group');
			 $this->tpl->assign("shopgroup", $shopgroup);
            $this->tpl->display("management/addshop.tpl");
        }
        if ($op == "addsaveshop") {
			$platformID= $this->input->post('platformID');
			
            $name=$this->input->post('updateoper');
            
            $res = $this->fun->getdatabasesdetail('db_platform'," AND id='".intval($platformID)."'");
          $platfromname = trim($res["name"]);
          $sql="select * from d_user where name='{$name}';";
          $ress = $this->db->query($sql)->result_array();
          $uploadID=trim($ress[0]["id"]);
           $updateoper = $name;
           $name =  $this->input->post('name');
		   $countryID =  $this->input->post('countryID');
           $platform = $platformID ;
           $descr =  $this->input->post('descr');
           $openflag=1;
           $amazonkey='';
           $creattime=date('Y-m-d H:i:s');
$sql2="INSERT INTO  `d_shop` (
`id` ,
`name` ,
`descr` ,
`creatoper` ,
`creattime` ,
`updateoper` ,
`uploadID` ,
`otherUpload` ,
`platfrom` ,
`platfromname` ,
`openflag` ,
`appkey` ,
`appsecret` ,
`refresh_token` ,
`refresh_timeout` ,
`access_token` ,
`access_timeout` ,
`amazonkey` ,
`aliexpressData` ,
`del_flag`,
`country`
)
VALUES (
NULL ,  '{$name}', '{$descr}' , NULL , '{$creattime}' ,  '{$updateoper}',  '{$uploadID}', NULL ,  '{$platformID}',  '{$platfromname}',  '{$openflag}', NULL , NULL , NULL , NULL , NULL , NULL , '{$amazonkey}', NULL ,  '0',  '{$countryID}'
);
";
$this->db->query($sql2);

			//如果是亚马迅的店铺，需要将店铺存入对应的订单搜索脚本
			if($platformID==2)
			{
				$list = $this->fun->getdatabaseslist('db_order_search'," AND  `name` like '%亚马逊%'");
				foreach($list as $key=>$rs)
				{
					$shopname = $rs['shopname'];
					$sqlfilter = $rs['sqlfilter'];
					$shopname = explode(";",$shopname);
					$oldshopname = implode("','",$shopname);
					$oldshopname = "'".$oldshopname."'";

					$newshop = $rs['shopname'].";".$this->input->post('name');
					$newshopst = explode(";",$newshop);
					$Newshopname = implode("','",$newshopst);
					$Newshopname = "'".$Newshopname."'";

					$newsql = str_replace($oldshopname,$Newshopname,$sqlfilter);
					$udata="";
					$udata['sqlfilter'] = $newsql;
					$udata['shopname'] = $newshop;
					$this->db->update('db_order_search',$udata," id='".$rs['id']."'");
				}
			}
            echo 200;
            die;
        }
        
		if ($op == "saveshop") {
			$res = $this->fun->getdatabasesdetail('db_platform'," AND id='".intval($this->input->post('platformID'))."'");
			$platfromname = trim($res["name"]);
			$id = $this->input->post('shopid');
			if($this->input->post('updateoper')==999999)
			{
				$updateoper = "";
			}else{
				$updateoper = $this->input->post('updateoper');
			}
			$shop_platform_fee = trim($this->input->post('shop_platform_fee'));
			$shop_pay_fee = trim($this->input->post('shop_pay_fee'));
			$user = $this->fun->userinfo(trim($this->input->post('updateoper')));
			 $this->db->update('d_shop',array('name'=>trim($this->input->post('name')),'country'=>trim($this->input->post('countryID')),'shop_pay_fee'=>$shop_pay_fee,'shop_platform_fee'=>$shop_platform_fee,'updateoper'=>$updateoper,'uploadID'=>$user["id"],'platfrom'=>$this->input->post('platformID'),'descr'=>trim($this->input->post('descr')),'platfromname'=>$platfromname),"id='".$id."'");
			
			 echo 200;
			 die;
        }
         //授权
        if($op == "auth"){
            $id         = $this->input->post('id');
			$Ali_agent_visit = $this->input->post('Ali_agent_visit');//1远程访问数据
            $arr_app['appkey']     = $this->input->post('key');
            $arr_app['appsecret']  = $this->input->post('secret');
			$arr_app['agent_visit']=$Ali_agent_visit;
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $rs  = $this->db->query($sql)->row_array();
            if($rs['platfromname']=='aliexpress'){
                $this->db->where('id',$id);
                $this->db->update('d_shop',$arr_app);

				
				if($Ali_agent_visit==1)
				{
					//保存到123数据库上的速卖通店铺信息
					$rsdb = $this->fun->getdatabasesdetail("d_shop"," AND id='".$id."'");
					$this->load->library('Amazondata');
					$ress = $this->amazondata->saveshop($rsdb);
					$data = array('code'=>0,'msg'=>'保存信息成功！请在远程机上面进行授权操作!');
					echo json_encode($data);exit;
				}else{
                //生成签名连接
					$appKey = $arr_app['appkey'];
					$appSecret = $arr_app['appsecret'];
				   // $arr_sign = $this->getSign($arr_app['appkey'],$arr_app['appsecret'],$id);
					//$redirectUrl = $this->url;//填写自己的回调地址
					$redirectUrl = $this->config->item('get_callback_url');  //回调地址需配置
					$state= $id;
					//生成签名，参数中state可不填
					$code_arr = array(
						'client_id' => $appKey,
						'redirect_uri' => $redirectUrl,
						'site' => 'aliexpress',
						'state'=>$state
					);
					$aliParams = array();
					foreach ($code_arr as $key => $val) {
						$aliParams[] = $key . $val;
					}
					sort($aliParams);
					$sign_str = join('',$aliParams);
					$code_sign = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
					$get_code_url = "http://gw.api.alibaba.com/auth/authorize.htm?client_id={$appKey}&site=aliexpress&state=$state&redirect_uri={$redirectUrl}&_aop_signature={$code_sign}";
					//生成签名结束
					//$data = array('code'=>1,'msg'=>"成功生成授权链接!",'url'=>$arr_sign['code_url']);
					$data = array('code'=>1,'msg'=>"成功生成授权链接!",'url'=>$get_code_url);
					echo json_encode($data);exit;
				}
            }else{
                $data = array('code'=>0,'msg'=>'非法操作!');
                echo json_encode($data);exit;
            }
        }
        //wish 授权
       if($op == "wishauth"){
            $id         = $this->input->post('wishid');
			$Ali_agent_visit = $this->input->post('wishagent_visit');//1远程访问数据
            $arr_wish=array('wishkey'=>$this->input->post('wishkey'),'wishsecret'=>$this->input->post('wishsecret'),'wishurl'=>$this->input->post('wishurl'));
            $arr_app['amazonkey']=json_encode($arr_wish);
			$arr_app['agent_visit']=$Ali_agent_visit;
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $rs  = $this->db->query($sql)->row_array();
            if($rs['platfromname']=='Wish'){
                $this->db->where('id',$id);
                $this->db->update('d_shop',$arr_app);
				
				if($Ali_agent_visit==1)
				{
					//保存到123数据库上的wish店铺信息
					$rsdb = $this->fun->getdatabasesdetail("d_shop"," AND id='".$id."'");
					$this->load->library('Amazondata');
					$ress = $this->amazondata->saveshop($rsdb);
					$data = array('code'=>0,'msg'=>"保存信息成功！请在远程机上面进行授权操作!",'url'=>'/management/setshop');
				     echo json_encode($data);exit;
				}else{
					//生成签名连接
					$appKey = $arr_wish['wishkey'];
					$get_code_url="https://merchant.wish.com/oauth/authorize?client_id={$appKey}";
					$data = array('code'=>1,'msg'=>"成功生成授权链接!",'url'=>$get_code_url);
					echo json_encode($data);exit;
				}
				
				
				
				
				
            }else{
                $data = array('code'=>0,'msg'=>'非法操作!');
                echo json_encode($data);exit;
            }
        }
         //ebay 授权
       if($op == "ebayauth"){

            $id= $this->input->post('ebayid');
            $arr_ebay=array('ebaydevid'=>$this->input->post('ebaydevid'),'ebayusertoken'=>$this->input->post('ebayusertoken'),'ebayappid'=>$this->input->post('ebayappid'),
            'ebaycertid'=>$this->input->post('ebaycertid'),'ebaycompatabilitylevel'=>$this->input->post('ebaycompatabilitylevel'),'ebaysiteid'=>$this->input->post('ebaysiteid'),'RuName'=>$this->input->post('RuName'));

            $agent_visit=$this->input->post('agent_visit');//是否远程代理访问
            $agent_site=$this->input->post('agent_site');//是否远程代理访问
            $arr_app['amazonkey']=json_encode($arr_ebay);
            $arr_app['agent_visit']=$agent_visit;
            $arr_app['agent_site']=$agent_site;
            $sql = "SELECT * FROM d_shop WHERE id = $id;";
            $rs  = $this->db->query($sql)->row_array();
            if($rs['platfromname']=='ebay'){
                $this->db->where('id',$id);
                $this->db->update('d_shop',$arr_app);
                
                if($agent_visit==1){
    				//保存到123数据库上的ebay店铺信息
    				$rsdb = $this->fun->getdatabasesdetail("d_shop"," AND id='".$id."'");
    				$this->load->library('Amazondata');
    				$ress = $this->amazondata->saveshop($rsdb);
    				//$data = array('code'=>1,'msg'=>"保存信息成功！请在远程机上面进行授权操作!",'url'=>'/management/setshop');
                    $data = array('code'=>1,'msg'=>"授权信息已存入");
					echo json_encode($data);exit;  
                }else{
                    //生成返回值
    				if($this->input->post('ebayusertoken')=="" || $this->input->post('ebayusertoken')==0){
    					$this->load->library('Ebaydata');
    					$sessioncode = $this->ebaydata->getuserToken($id);	//获取session第一步
					
    					if($sessioncode == false)
    					{
    						$data = array('code'=>0,'msg'=>'获取授权失败，请联系管理员!');
    						echo json_encode($data);exit;
    					}else{
    						$RuName = $sessioncode['RuName'];
    						$arrebay=array('ebaydevid'=>$this->input->post('ebaydevid'),'ebayusertoken'=>$this->input->post('ebayusertoken'),'ebayappid'=>$this->input->post('ebayappid'),'ebaycertid'=>$this->input->post('ebaycertid'),'ebaycompatabilitylevel'=>$this->input->post('ebaycompatabilitylevel'),'ebaysiteid'=>$this->input->post('ebaysiteid'),'RuName'=>$RuName,'SessionID'=>$sessioncode['SessionID']);
    						$arrapp['amazonkey']=json_encode($arrebay);
    						$this->db->where('id',$id);
    						$this->db->update('d_shop',$arrapp);
    	
    						
    						$url = "https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RuName={$RuName}&SessID=".$sessioncode['SessionID'];
    						$data = array('code'=>1,'msg'=>'请点击“确定”打开授权页面进行授权','url'=>$url);
    						echo json_encode($data);exit;
    					}
    					$data = array('code'=>1,'msg'=>"授权信息已存入");
    					echo json_encode($data);exit;  
    				}
    				$data = array('code'=>1,'msg'=>"保存成功");
                    echo json_encode($data);exit;  
                }
            }else{
                $data = array('code'=>0,'msg'=>'非法操作!');
                echo json_encode($data);exit;
            }
        }
		if($op =='shouquanebayauth')
		{
			$id= $this->input->post('ebayid');
			$this->load->library('Ebaydata');
			$token = $this->ebaydata->getuserTokensecond($id);	//获取session第一步
			if($token != false)
			{
				$sql = "SELECT * FROM d_shop WHERE id = $id";
				$rs  = $this->db->query($sql)->row_array();
				$arrapp=json_decode($rs['amazonkey'],true);
				$arrebay=array('ebaydevid'=>$arrapp['ebaydevid'],'ebayusertoken'=>$token,'ebayappid'=>$arrapp['ebayappid'],'ebaycertid'=>$arrapp['ebaycertid'],'ebaycompatabilitylevel'=>$arrapp['ebaycompatabilitylevel'],'ebaysiteid'=>$arrapp['ebaysiteid'],'RuName'=>$arrapp['RuName'],'SessionID'=>$arrapp['SessionID'][0]);
				$arrappnr['amazonkey']=json_encode($arrebay);
				$this->db->where('id',$id);
                $this->db->update('d_shop',$arrappnr);
				$data = array('code'=>1,'msg'=>"授权信息已存入","token"=>$token);
                echo json_encode($data);exit;
				
			}else{
				$data = array('code'=>0,'msg'=>"授权失败");
                echo json_encode($data);exit;
			}

		}

		if($op =="saveamazon")
		{
			$arr_app['id']= $id = $this->input->post('id');
            $arr_app['SellerId']     = trim($this->input->post('stkey'));
            $arr_app['SecretKey']  = trim($this->input->post('stsecretkey'));
            $arr_app['ACCESSID']     = trim($this->input->post('ACCESSId'));
            $arr_app['MarketplaceId']  = trim($this->input->post('MarketplaceId'));
			$arr_app['serverurl']  = trim($this->input->post('SERVERURL'));
			$arr_app['timezone']  = trim($this->input->post('timezone'));
			$amazonkey = serialize($arr_app);
			if($amazonkey)
			{
				$this->db->update('d_shop',array('amazonkey'=>$amazonkey),"id='".$id."'");
			}

			//保存到123数据库上的amazon 信息
			$rsdb = $this->fun->getdatabasesdetail("d_shop"," AND id='".$id."'");
			$this->load->library('Amazondata');
			$ress = $this->amazondata->saveshop($rsdb);
		
			echo $id;
			die;
		
		}
        //删除
        if ($op == "del"){
            $id = $this->input->post('id');
            $data['del_flag'] = 1; //删除标记
            $this->db->where('id',$id);
            $this->db->update('d_shop',$data);
            if($this->db->affected_rows()){
                $arr_back = array('code'=>1,'msg'=>'删除成功!');
            }else{
                $arr_back = array('code'=>0,'msg'=>'删除失败');
            }
            echo json_encode($arr_back);exit;

        }
        //如果存在密钥则显示(授权按钮)
        if ($op == "getkey"){
            $id = $this->input->post('id');
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $arr_row = $this->db->query($sql)->row_array();
            if(!empty($arr_row)){
				if($arr_row["amazonkey"])
				{
					$amazonkey = unserialize($arr_row["amazonkey"]);
				}
                $arr_back = array('code'=>1,'msg'=>'获取成功!','key'=>$arr_row['appkey'],'secret'=>$arr_row['appsecret'],'amazonkey'=>$amazonkey);
            }else{
                $arr_back = array('code'=>0,'msg'=>'获取失败');
            }
            echo json_encode($arr_back);exit;

         }
        //whis如果存在密钥则显示(授权按钮)
        if ($op == "getwishkey"){
            $id = $this->input->post('id');
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $arr_row = $this->db->query($sql)->row_array();
            if(!empty($arr_row)){
                if($arr_row["amazonkey"])
                {
                    $amazonkey = json_decode($arr_row["amazonkey"],true);
                }else{
                    $amazonkey = array('wishkey'=>'0','wishsecret'=>'0');
                }
                $arr_back = array('code'=>1,'msg'=>'获取成功!','key'=>$amazonkey['wishkey'],'secret'=>$amazonkey['wishsecret'],'wishurl'=>$amazonkey['wishurl'],'agent_visit'=>$arr_row['agent_visit']);
            }else{
                $arr_back = array('code'=>0,'msg'=>'获取失败');
            }
            echo json_encode($arr_back);exit;

        }
  //ebay如果存在密钥则显示(授权按钮)
        if ($op == "getebaykey"){
            $id = $this->input->post('ebayid');
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $arr_row = $this->db->query($sql)->row_array();
            if(!empty($arr_row)){
                if($arr_row["amazonkey"])
                {
                    $amazonkey = json_decode($arr_row["amazonkey"],true);
                }else{
                    $amazonkey = array('ebaydevid'=>'0','ebayusertoken'=>'0','ebayappid'=>'0','ebaycertid'=>'0','ebaycompatabilitylevel'=>'0','ebaysiteid'=>'0');
                }
				$RuName = $amazonkey['RuName']?$amazonkey['RuName']:$amazonkey['RuName'];
                $arr_back = array('code'=>1,'msg'=>'获取成功!','agent_visit'=>$arr_row['agent_visit'],'agent_site'=>$arr_row['agent_site'],'ebaydevid'=>$amazonkey['ebaydevid'],'RuName'=>$RuName,'ebayusertoken'=>$amazonkey['ebayusertoken'],'ebayappid'=>$amazonkey['ebayappid'],'ebaycertid'=>$amazonkey['ebaycertid'],'ebaycompatabilitylevel'=>$amazonkey['ebaycompatabilitylevel'],'ebaysiteid'=>$amazonkey['ebaysiteid']);
            }else{
                $arr_back = array('code'=>0,'msg'=>'获取失败');
            }
            echo json_encode($arr_back);exit;

        }

 //magento如果存在密钥则显示(授权按钮)
        if ($op == "getmagentokey"){
            $id = $this->input->post('magentoid');
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $arr_row = $this->db->query($sql)->row_array();
            if(!empty($arr_row)){
                if($arr_row["amazonkey"])
                {
                    $amazonkey = json_decode($arr_row["amazonkey"],true);
                }else{
                    $amazonkey = array('magentotoken'=>0,'magentourl'=>0);
                }
                $arr_back = array('code'=>1,'msg'=>'获取成功!','magentotoken'=>$amazonkey['magentotoken'],'magentourl'=>$amazonkey['magentourl'],'magento1_user'=>$amazonkey['magento1_user'],'magento1_key'=>$amazonkey['magento1_key'],'magento2_consumerkey'=>$amazonkey['magento2_consumerkey'],'magento2_consumersecret'=>$amazonkey['magento2_consumersecret'],'magento2_accesstoken'=>$amazonkey['magento2_accesstoken'],'magento2_accesstokensecret'=>$amazonkey['magento2_accesstokensecret'],'magento2_username'=>$amazonkey['magento2_username'],'magento2_password'=>$amazonkey['magento2_password'],'magentov'=>$amazonkey['magentov']);
            }else{
                $arr_back = array('code'=>0,'msg'=>'获取失败');
            }
            echo json_encode($arr_back);exit;

        }
           //magento 授权
       if($op == "magentoauth"){

            $id= $this->input->post('magentoid');
            $arr_magento=array('magentotoken'=>$this->input->post('magentotoken'),'magentourl'=>$this->input->post('magentourl'),'magento1_user'=>$this->input->post('magento1_user'),'magento1_key'=>$this->input->post('magento1_key'),'magento2_consumerkey'=>$this->input->post('magento2_consumerkey'),'magento2_consumersecret'=>$this->input->post('magento2_consumersecret'),'magento2_accesstoken'=>$this->input->post('magento2_accesstoken'),'magento2_accesstokensecret'=>$this->input->post('magento2_accesstokensecret'),'magento2_username'=>$this->input->post('magento2_username'),'magento2_password'=>$this->input->post('magento2_password'),'magentov'=>$this->input->post('magentov'));
            $arr_app['amazonkey']=json_encode($arr_magento);
            $sql = "SELECT * FROM d_shop WHERE id = $id;";
            $rs  = $this->db->query($sql)->row_array();
            if($rs['platfromname']=='Magento'){
                $this->db->where('id',$id);
                $this->db->update('d_shop',$arr_app);
                //生成返回值
				
				//保存到123数据库上的amazon 信息
				$rsdb = $this->fun->getdatabasesdetail("d_shop"," AND id='".$id."'");
				$this->load->library('Amazondata');
				$ress = $this->amazondata->saveshop($rsdb);

                $data = array('code'=>1,'msg'=>"授权信息已存入");
                echo json_encode($data);exit;
            }else{
                $data = array('code'=>0,'msg'=>'非法操作!');
                echo json_encode($data);exit;
            }
        }
       //shopee获取秘钥
      if ($op == "getshopeekey"){
            $id = $this->input->post('shopeeid');
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $arr_row = $this->db->query($sql)->row_array();
            if(!empty($arr_row)){
                if($arr_row["amazonkey"])
                {
                    $amazonkey = json_decode($arr_row["amazonkey"],true);
                }else{
                    $amazonkey = array('shopeetoken'=>0);
                }
                $arr_back = array('code'=>1,'msg'=>'获取成功!','shopeetoken'=>$amazonkey['shopeetoken']);
            }else{
                $arr_back = array('code'=>0,'msg'=>'获取失败');
            }
            echo json_encode($arr_back);exit;

        }

              //shopee获取秘钥
      if ($op == "getshopifykey"){
            $id = $this->input->post('shopifyid');
            $sql = "SELECT * FROM d_shop WHERE id = $id ";
            $arr_row = $this->db->query($sql)->row_array();
            if(!empty($arr_row)){
                if($arr_row["amazonkey"])
                {
                    $amazonkey = json_decode($arr_row["amazonkey"],true);
                }else{
                    $amazonkey = array('shopifytoken'=>0);
                }
                $arr_back = array('code'=>1,'msg'=>'获取成功!','shopifytoken'=>$amazonkey['shopifytoken']);
            }else{
                $arr_back = array('code'=>0,'msg'=>'获取失败');
            }
            echo json_encode($arr_back);exit;

        }

    //shopee授权
      if($op == "shopeeauth"){

            $id         = $this->input->post('shopeeid');
            $arr_shopee=array('shopeetoken'=>$this->input->post('shopeetoken'));
            $arr_app['amazonkey']=json_encode($arr_shopee);
            $sql = "SELECT * FROM d_shop WHERE id = $id;";
            $rs  = $this->db->query($sql)->row_array();
            if($rs['platfromname']=='Shopee'){
                $this->db->where('id',$id);
                $this->db->update('d_shop',$arr_app);
                //生成返回值
                $data = array('code'=>1,'msg'=>"授权信息已存入");
                echo json_encode($data);exit;
            }else{
                $data = array('code'=>0,'msg'=>'非法操作!');
                echo json_encode($data);exit;
            }
        }

            //shopify授权
      if($op == "shopifyauth"){

            $id         = $this->input->post('shopifyid');
            $arr_shopee=array('shopifytoken'=>$this->input->post('shopifytoken'));
            $arr_app['amazonkey']=json_encode($arr_shopee);
            $sql = "SELECT * FROM d_shop WHERE id = $id;";
            $rs  = $this->db->query($sql)->row_array();
            if($rs['platfromname']=='Shopify'){
                $this->db->where('id',$id);
                $this->db->update('d_shop',$arr_app);
                //生成返回值
                //店铺名称
                $shop = $arr_shopee['shopifytoken'];
                //app key 在开发者平台中创建app就会生成
				$api_key = "daeaac41584625af84a5707f708336f6";
				//权限
				$scopes = "read_content,write_content,read_themes,write_themes,read_products,write_products,read_product_listings,read_collection_listings,read_customers,write_customers,read_orders,write_orders,read_draft_orders,write_draft_orders,read_script_tags,write_script_tags,read_fulfillments,write_fulfillments,read_shipping,write_shipping,read_analytics,read_checkouts,write_checkouts,read_reports,write_reports,read_price_rules,write_price_rules,read_marketing_events,write_marketing_events,read_resource_feedbacks,write_resource_feedbacks";
				//返回地址
				$redirect_uri = "https://notwork.ffcosplay.com/shopify/index.php";
				//构建请求地址
				$install_url = "https://" . $shop . ".myshopify.com/admin/oauth/authorize?client_id=" . $api_key . "&scope=" . $scopes . "&redirect_uri=" . urlencode($redirect_uri);
				// 跳转授权请求页面内页面会生成授权信息，
                //header("Location: " . $install_url);
                // echo "< script language='javascript' type='text/javascript'>";  
                // echo "window.location.href='$install_url'";  
                // echo "< /script>"; 
                //die();
                $data = array('code'=>1,'msg'=>$install_url);
                echo json_encode($data);exit;
            }else{
                $data = array('code'=>0,'msg'=>'非法操作!');
                echo json_encode($data);exit;
            }
        }


    }








}
